package com.zn.jdwl.base;
import java.io.Serializable;
import java.util.Stack;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;

public class MLAppManager {
	
	private static Stack<Activity> activityStack;
	private static MLAppManager instance;
	
	private MLAppManager(){}

	public static MLAppManager getAppManager(){
		if(instance==null){
			instance=new MLAppManager();
		}
		return instance;
	}

	public void addActivity(Activity activity){
		if(activityStack==null){
			activityStack=new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	public Activity currentActivity(){
		Activity activity=activityStack.lastElement();
		return activity;
	}

	public void finishActivity(){
		Activity activity=activityStack.lastElement();
		finishActivity(activity);
	}

	public void finishActivity(Activity activity){
		if(activity!=null){
			activityStack.remove(activity);
			activity.finish();
			activity=null;
		}
	}
	
	public void finishActivity(Class<?> cls){
		for (Activity activity : activityStack) {
			if(activity.getClass().equals(cls) ){
				finishActivity(activity);
			}
		}
	}
	
	public void finishAllActivity(){
		for (int i = 0, size = activityStack.size(); i < size; i++){
            if (null != activityStack.get(i)){
            	activityStack.get(i).finish();
            }
	    }
		activityStack.clear();
	}
	
	
	public  static void startActivity(Activity act , Class cls,Object obj,int requestCode){
		Intent intent = new Intent();
		intent.setClass(act, cls);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
	//	intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);  
		if(obj!=null){
			intent.putExtra(MLBaseConstants.TAG_INTENT_DATA, (Serializable)obj);
		}
		
		if(requestCode!=-1){
			act.startActivityForResult(intent, requestCode);
		}else{
			act.startActivity(intent);
		}
	}
	
	

	public  static void startActivityForFrg(Fragment act , Class cls,Object obj,int requestCode){
		Intent intent = new Intent();
		intent.setClass(act.getActivity(), cls);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
	//	intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);  
		if(obj!=null){
			intent.putExtra(MLBaseConstants.TAG_INTENT_DATA, (Serializable)obj);
		}
		
		if(requestCode!=-1){
			act.startActivityForResult(intent, requestCode);
		}else{
			act.startActivity(intent);
		}
	}
	
	

	public void AppExit(Context context) {
		try {
			finishAllActivity();
			ActivityManager activityMgr= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			activityMgr.restartPackage(context.getPackageName());
			System.exit(0);
		} catch (Exception e) {	}
	}
}